#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of KeyExtracta
# <http://code.google.com/p/keyextracta/>.
#
# KeyExtracta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# KeyExtracta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with KeyExtracta.  If not, see <http://www.gnu.org/licenses/>.

from PyQt4.QtGui import QMainWindow, QDesktopServices, QFileDialog, QCursor     
from PyQt4.QtCore import SIGNAL, SLOT, QUrl, QCoreApplication, Qt
from src.ui.ui_mainWindow import Ui_MainWindow
from core import msKeyDecoder, structures, keyRetrieval

class MainWindow(QMainWindow, Ui_MainWindow):
  def __init__(self):
    """"""
    super(QMainWindow, self).__init__()
    self.setupUi(self)
    
    self.connect(self.actionExit, SIGNAL("triggered()"), self, SLOT("close()"))
    self.listWidget.itemSelectionChanged.connect(self.keySelected)
    
    # QListWidget
    self.connect(self.listWidget,
      SIGNAL('customContextMenuRequested(const QPoint&)'),
      self.listWidgetContextMenu
    )
    # QSplitter
    self.connect(self.splitter, SIGNAL('doubleClicked(int,int)'),
      self.splitterDoubleClicked)
    self.createContextMenus()
    
    # QActions
    self.actionExport_Selected.triggered.connect(self.exportSelected)
    self.actionExport_All.triggered.connect(self.exportAll)
    self.actionPrint.triggered.connect(self.printAll)
    self.actionRefresh.triggered.connect(self.reloadFields)
    self.actionHomepage.triggered.connect(self.openHomepage)
    self.actionWiki.triggered.connect(self.openWiki)
    self.actionAbout.triggered.connect(self.callAbout)
    
    # Load all fields
    self.loadFields()
  
  def printAll(self):
    """Print all keys"""
    from PyQt4.QtGui import QPrinter, QPrintDialog, QDialog, QTextDocument
    printer = QPrinter()
    printDialog = QPrintDialog(printer, self)
    if (printDialog.exec_() != QDialog.Accepted):
      return
    text = structures.formatAllKeys(keyList)
    doc = QTextDocument(structures.addHeader(text))
    doc.print_(printer)
  
  def splitterDoubleClicked(self, a, b):
    """What to perform when QSplitter is double clicked with left button"""
    if b is 1:
      self.resizeListWidget()
    
  def callAbout(self):
    """Open the About dialog"""
    from core.aboutDialogActions import AboutDialog
    self.aboutDialog = AboutDialog(self)
    self.aboutDialog.exec_()
    
  def createContextMenus(self):
    """Create context menus for the QListWidget"""
    from PyQt4.QtGui import QMenu
    self.contextMenu = QMenu(self)
    self.contextMenu.addAction(self.actionExport_All)
    self.contextMenu.addSeparator()
    self.contextMenu.addAction(self.actionRefresh)
 
    self.contextMenuSelected = QMenu(self)
    self.contextMenuSelected.addAction(self.actionExport_Selected)
    self.contextMenuSelected.addAction(self.actionExport_All)
    self.contextMenuSelected.addSeparator()
    self.contextMenuSelected.addAction(self.actionRefresh)
  
  def listWidgetContextMenu(self):
    """Open up the proper context menu of the QListWidget"""
    pos = QCursor.pos()
    item = self.listWidget.itemAt(self.listWidget.viewport().mapFromGlobal(pos))
    if item is None:
      self.contextMenu.exec_(pos)
    else:
      self.contextMenuSelected.exec_(pos)
    
  def writeFile(self, text, file):
    """Write text to file"""
    try:
      with open(file, 'w') as f:
        f.write(text)
    except IOError:
      print "Error: can\'t find file or read data"

  def selectedItem(self):
    """Return the text of the selected item in the QListWidget"""
    return self.listWidget.selectedItems()[0].text()
  
  def plainTextEditText(self):
    """Return the text"""
    return self.plainTextEdit.toPlainText()
    
  def exportSelected(self):
    """Export selected key to text file"""
    item = self.selectedItem()
    filename = QFileDialog.getSaveFileName(self, 'Export Selected Key',
      '%s.txt' % item, 'Text file (*.txt)')
    if filename:
      text = self.plainTextEditText()
      self.writeFile(structures.addHeader(text), filename)
  
  def exportAll(self):
    """Export all keys to text file"""
    f = structures.formatExportFileName()
    filename = QFileDialog.getSaveFileName(self, 'Export All Keys',
      '%s.txt' % f, 'Text file (*.txt)')
    if filename:
      text = structures.formatAllKeys(keyList)
      self.writeFile(structures.addHeader(text), filename)
    
  def openHomepage(self):
    """Open homepage"""
    self.openURL(QCoreApplication.organizationDomain())
    
  def openWiki(self):
    """Open Wiki page"""
    url = '/'.join([str(QCoreApplication.organizationDomain()).rstrip('/'),
      'wiki', 'GettingStarted?tm=6'])
    self.openURL(url)
    
  def keySelected(self):
    """Actions to perform when QListWidget is selected"""
    self.setTextEdit(self.listWidget.currentRow())
    
  def setTextEdit(self, idx):
    """Set QTextEdit"""
    text = structures.formatKey(keyList[idx])
    self.plainTextEdit.setPlainText(text)
    
  def loadListWidget(self):
    """Load the QListWidget"""
    if len(keyList) > 0:
      self.listWidget.addItems(structures.getNames(keyList))
    self.resizeListWidget()
    
  def resizeListWidget(self):
    """Resize QListWidget based on longest item"""
    splitterWidth = self.splitter.sizeHint().width()
    listWidth = int(self.listWidget.sizeHintForColumn(0))
    self.splitter.setSizes([listWidth, splitterWidth-listWidth])
  
  def reloadFields(self):
    """Rescan registry and reload fields"""
    self.listWidget.clear()
    self.loadFields()
    
  def loadFields(self):
    """Load fields"""
    self.getKeys()
    self.loadListWidget()
    self.setTextEdit(0)
    self.listWidget.setCurrentRow(0)
    
  def getKeys(self):
    """Get all keys"""
    global keyList
    keyList = []
    self.appendKeys(msKeyDecoder.getWinKey())
    self.appendKeys(msKeyDecoder.getOfficeKeys())
    self.appendKeys(keyRetrieval.getKeys())

  def appendKeys(self, k, m=None):
    """Append to keyList"""
    global keyList
    if k is not None:
      keyList += k
  
  def openURL(self, url):
    """Open URL in default browser"""
    QDesktopServices.openUrl(QUrl(url))

  def closeEvent(self, event):
    """Run when application is closed"""
    event.accept()